package com.example.messagemodule.ui;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.example.messagemodule.R;
import com.example.messagemodule.entity.HealthConsultDetailEntity;
import com.example.messagemodule.ui.fragment.HealthConsultArticleFragment;
import com.example.messagemodule.ui.fragment.HealthConsultNoiceFragment;
import com.example.messagemodule.ui.fragment.HealthConsultVideoFragment;
import com.example.messagemodule.utils.MessageUtils;
import com.google.gson.Gson;
import com.shicheng.mediaplayer.AudioSensorBinder;
import com.shicheng.mediaplayer.media.MediaManager;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DataUtils;
import com.yilijk.base.utils.DevicesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import crossoverone.statuslib.StatusUtil;

@Route(path = ARouterConstants.HealthConsultDetailActivity)
public class HealthConsultDetailActivity extends ModuleBaseActivity implements LifecycleOwner {


    //LifecycleRegistry 实现了Lifecycle
    private LifecycleRegistry mLifecycleRegistry=new LifecycleRegistry(HealthConsultDetailActivity.this);
    AudioSensorBinder audioSensorBinder;;
    @Autowired
    int rowType; //0 文章 1 音频 2 视频
    @Autowired
    String rowKey;

    HealthConsultArticleFragment healthConsultArticleFragment;
    HealthConsultNoiceFragment healthConsultNoiceFragment;
    HealthConsultVideoFragment healthConsultVideoFragment;


    private LinearLayout healthDetailLinear;
    private SeekBar healthDetailSeekProgress;
    private TextView healthDetailCurrent;
    private TextView healthDetailTotal;
    private FrameLayout healthDetailReduce;
    private ImageView healthDetailState;
    private FrameLayout healthDetailAdd;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private Timer timer;
    SimpleDateFormat format;
    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。



    FrameLayout frameLayout_healthConsult;
    TextView healthConsultTitle;
    TextView healthConsultTime;


    private Handler handler = new Handler();

    @Override
    public int bondLayout() {
        return R.layout.activity_health_consult_detail;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView() {
        audioSensorBinder = new AudioSensorBinder(this);
        mLifecycleRegistry.addObserver(audioSensorBinder);

        frameLayout_healthConsult = findViewById(R.id.healthConsult_frame);
        healthConsultTitle = findViewById(R.id.healthConsult_title);
        healthConsultTime = findViewById(R.id.healthConsult_time);

        StatusUtil.setSystemStatus(this,false,true);
        StatusUtil.setUseStatusBarColor(this, Color.WHITE);
        healthDetailLinear = (LinearLayout) findViewById(R.id.health_detail_linear);
        healthDetailSeekProgress = (SeekBar) findViewById(R.id.health_detail_seek_progress);
        healthDetailCurrent = (TextView) findViewById(R.id.health_detail_current);
        healthDetailTotal = (TextView) findViewById(R.id.health_detail_total);
        healthDetailReduce = (FrameLayout) findViewById(R.id.health_detail_reduce);
        healthDetailState = (ImageView) findViewById(R.id.health_detail_state);
        healthDetailAdd = (FrameLayout) findViewById(R.id.health_detail_add);
        healthDetailSeekProgress.setOnSeekBarChangeListener(new MySeekBar());
        healthDetailLinear.setVisibility(View.GONE);
        if (rowType == 0){
            //文章
            healthConsultArticleFragment = new HealthConsultArticleFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.healthConsult_frame,healthConsultArticleFragment).commit();

        }else if (rowType == 1){
            healthDetailLinear.setVisibility(View.VISIBLE);
            //音频
//            healthConsultNoiceFragment = new HealthConsultNoiceFragment();
//            getSupportFragmentManager().beginTransaction().replace(R.id.healthConsult_frame,healthConsultNoiceFragment).commit();
            healthConsultArticleFragment = new HealthConsultArticleFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.healthConsult_frame,healthConsultArticleFragment).commit();
        }else{
            //视频
            healthConsultVideoFragment = new HealthConsultVideoFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.healthConsult_frame,healthConsultVideoFragment).commit();

        }



    }

    @Override
    public void initData() {
        format = new SimpleDateFormat("mm:ss");
        getHealthConsultDetailData();

    }

    @Override
    public void initEvent() {

        ClickUtils.setFastOnClickListener(findViewById(R.id.healthConsult_back), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        healthDetailState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mediaPlayer.isPlaying()) {
                    healthDetailState.setBackground(getResources().getDrawable(R.drawable.media_play));
                    mediaPlayer.start();//开始播放
                    mediaPlayer.seekTo(healthDetailSeekProgress.getProgress());

                    //监听播放时回调函数
                    timer = new Timer();
                    timer.schedule(new TimerTask() {

                        Runnable updateUI = new Runnable() {
                            @Override
                            public void run() {
                                if (mediaPlayer!=null && mediaPlayer.getCurrentPosition()!=-1){
                                    healthDetailCurrent.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                                }
                            }
                        };

                        @Override
                        public void run() {
                            if (!isSeekBarChanging) {
                                healthDetailSeekProgress.setProgress(mediaPlayer.getCurrentPosition());
                                runOnUiThread(updateUI);
                            }
                        }
                    }, 0, 50);
                } else {
                    healthDetailState.setBackground(getResources().getDrawable(R.drawable.media_stop));
                    mediaPlayer.pause();//暂停播放
                }
            }
        });
        //加15s
        healthDetailAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.seekTo(healthDetailSeekProgress.getProgress() + 15000);
            }
        });
        //减15s
        healthDetailReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.seekTo(healthDetailSeekProgress.getProgress() - 15000);
            }
        });
    }


    private void initMediaPlayer(String url) {
        try {
            mediaPlayer.setDataSource(url);//指定音频文件的路径
            mediaPlayer.prepare();//让mediaplayer进入准备状态
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    healthDetailSeekProgress.setMax(mediaPlayer.getDuration());
                    healthDetailTotal.setText(format.format(mediaPlayer.getDuration()) + "");
                    healthDetailCurrent.setText("00:00");
                }
            });
            // 监听音频播放完的代码，实现音频的自动循环播放
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer arg0) {
                    healthDetailState.setBackground(getResources().getDrawable(R.drawable.media_stop));
                }
            });
//            mediaPlayer.start();//开始播放
//            mediaPlayer.seekTo(0);
            healthDetailState.setBackground(getResources().getDrawable(R.drawable.media_stop));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //监听播放时回调函数
//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//
//            Runnable updateUI = new Runnable() {
//                @Override
//                public void run() {
//                    if (mediaPlayer != null) {
//                        healthDetailCurrent.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
//                    }
//                }
//            };
//
//            @Override
//            public void run() {
//                if (!isSeekBarChanging) {
//                    healthDetailSeekProgress.setProgress(mediaPlayer.getCurrentPosition());
//                    runOnUiThread(updateUI);
//                }
//            }
//        }, 0, 50);
    }

    void getHealthConsultDetailData(){
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("rowKey",rowKey);
        HttpUtils.get(AllStringConstants.MessageUrl.Get, jsonObject, new HttpCallBack<HealthConsultDetailEntity>() {
            @Override
            public void onSuccess(HealthConsultDetailEntity healthConsultDetailEntity, int i) {
                if (healthConsultDetailEntity.isResult() && healthConsultDetailEntity.getData()!=null){
                    HealthConsultDetailEntity.DataBean data = healthConsultDetailEntity.getData();
                    refreshUi(data);
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });


    }


    private void refreshUi(HealthConsultDetailEntity.DataBean data) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (data.getTitle()!=null){
                    healthConsultTitle.setText(data.getTitle());
                }
                if (data.getPushTime()!=-1){
                    String s = DataUtils.long2string(data.getPushTime(), "yyyy-MM-dd");
                    healthConsultTime.setText("发表于"+s);
                }
            }
        });



        if (rowType == 0){
            if (data.getContent()!=null){
                healthConsultArticleFragment.setContent(data.getContent());
                healthConsultArticleFragment.refreshFragment();
            }
        }else if(rowType == 1){
//            if (data.getContent()!=null && data.getResourceUrl()!=null){
//                healthConsultNoiceFragment.setUrl(data.getResourceUrl(),data.getContent());
//                healthConsultNoiceFragment.refreshFragment();
//            }
            if (data.getContent()!=null){
                healthConsultArticleFragment.setContent(data.getContent());
                healthConsultArticleFragment.refreshFragment();
            }
            if (data.getResourceUrl()!=null && data.getResourceUrl().startsWith("http")){
                initMediaPlayer(data.getResourceUrl());
            }

        }else if(rowType == 2){
            if (data.getResourceUrl()!=null){
                healthConsultVideoFragment.setUrl(data.getResourceUrl(),data.getContent());
                healthConsultVideoFragment.refreshFragment();
            }
        }else{

        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        isSeekBarChanging = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (healthConsultNoiceFragment!=null){
            MediaManager.removeAll();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pageName","HealthConsultDetail");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MessageUtils.sendBrocast(this, "ReceiveRefreshKey", jsonObject.toString());
        mLifecycleRegistry.removeObserver(audioSensorBinder);
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        healthConsultVideoFragment.setSavedPosition(data.getIntExtra("currentPosition",0));
    }
}